package com.bric.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.concurrent.ConcurrentLinkedDeque;

import org.apache.log4j.Logger;

public class JdbcFactory {
	private static final Logger log=Logger.getLogger(JdbcFactory.class);
	/*private static ConcurrentLinkedDeque<Connection> conn;
	private static JdbcFactory jdbcFactory;
	private static void  initJdbcCon(){
		conn=new ConcurrentLinkedDeque<Connection>();
		if(null!=StaticStr.jdbcPoolSize){
			int ps=Integer.parseInt(StaticStr.jdbcPoolSize);
			for(int i=0;i<ps;i++){
				Connection con_acc=null;
				try {
					Class.forName(StaticStr.driverClass);
					con_acc=DriverManager.getConnection(StaticStr.jdbcUrl, StaticStr.username, StaticStr.password);
				} catch (ClassNotFoundException e) {
					log.info(e.getMessage());
				} catch (SQLException e) {
					log.info(e.getMessage());
				}
				conn.add(con_acc);
			}
		}
	}
	public static JdbcFactory getJdbcFactory() {
		if(null==jdbcFactory){
			synchronized (JdbcFactory.class) {
				if(null==jdbcFactory){
					jdbcFactory=new JdbcFactory();
				}
			}
		}
		return jdbcFactory;
	}
	private JdbcFactory() {
		initJdbcCon();
	}
	public Connection getConn() throws Exception{
		if(null!=conn&&conn.size()>0){
			return conn.remove();
		}else{
			throw new Exception("连接已使用完毕");
		}
	}
	public void close(Connection con){
		conn.add(con);
	}*/
	
	public static Connection getConnection(){
		Connection con_bric=null;
		try {
			Class.forName(StaticStr.driverClass);
			con_bric=DriverManager.getConnection(StaticStr.jdbcUrl, StaticStr.username, StaticStr.password);
		} catch (ClassNotFoundException e) {
			log.error("找不到驱动类"+e.getMessage());
		} catch (SQLException e) {
			log.error("获取数据库连接失败"+e.getMessage());
		}
		return con_bric;
	}
	public static void close(Connection con,PreparedStatement ps,ResultSet rs){
		try {
			if(null!=rs){
				rs.close();
			}
			if(null!=ps){
				ps.close();
			}
			if(null!=con){
				con.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
			log.error("关闭失败"+e.getMessage());
		}
	}
	public static void close(Connection con,PreparedStatement ps){
		close(con, ps, null);
	}
	public static void close(Connection con){
		close(con, null, null);
	}
	/*public static void main(String[] args) {
		Connection conn=JdbcFactory.getConnection();
		PreparedStatement ps=null;
		ResultSet rs=null;
		try {
			ps=conn.prepareStatement("select * from accfutures.acity");
			rs=ps.executeQuery();
			while(rs.next()){
				System.out.println(rs.getString(1));
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			JdbcFactory.close(conn, ps, rs);
		}
	}*/
}
